package com.chungkui.check.handler.impl;

import com.chungkui.check.configparser.bean.CheckConfig;
import com.chungkui.check.core.bean.CheckResult;
import com.chungkui.check.expression.MatchExpression;
import com.chungkui.check.handler.CheckHandler;
import com.chungkui.check.handler.insidecheck.ParamCheckUtils;
import com.googlecode.aviator.Expression;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;

/**
 * @Author: jason
 * @Date: 2019/12/30 16:51
 * @Version 1.0
 */

public class ParamCheckHandler implements CheckHandler {
    private final Logger log = LoggerFactory.getLogger(ParamCheckHandler.class);

    @Override
    public CheckResult check(CheckConfig checkConfig, Map<String, Object> params) {
        List<MatchExpression> matchExpressions = checkConfig.getMatchExpressions();
        //全局触发条件，整个方法级别的
        Expression condition = checkConfig.getCondition();
        if (condition != null) {
            boolean result;
            try {
                result = (Boolean) condition.execute(params);
            } catch (Exception e) {
                result = false;
                log.info("condition match  fail", e);
            }
            //不触发
            if (!result) {
                return new CheckResult(true);
            }
        }
        if (CollectionUtils.isNotEmpty(matchExpressions)) {
            return check(matchExpressions, params);
        }
        return new CheckResult(true);
    }

    /**
     * 执行校验
     *
     * @param matchExpressions
     * @param params
     * @return
     */
    private CheckResult check(List<MatchExpression> matchExpressions, Map<String, Object> params) {
        CheckResult result = ParamCheckUtils.check(matchExpressions, params);
        if (!result.ifPass()) {
            return result;
        }
        return new CheckResult(true);
    }

    @Override
    public int sort() {
        return 4;
    }
}
